package com.jiuyin.dianjing.ui.activity.setting;

import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.google.gson.JsonObject;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.api.base.DefaultApiResult;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.ui.activity.base.BaseActivity;
import com.jiuyin.dianjing.util.ToastUtil;

import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_PASSWORD;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.util.DesUtil.getMd5;

/**
 * 确认新密码
 */
public class ConfirmNewPwdActivity extends BaseActivity {
    @BindView(R.id.edt_pwd_new)
    EditText mNewPhone;
    @BindView(R.id.edt_pwd_new_confirm)
    EditText mNewPhoneConfirm;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_modify_confirm_pwd;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        setTitle(R.string.setting_modify_pwd);
    }

    @OnClick({R.id.tv_done})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_done:
                changePwd();
                break;
        }
    }

    /**
     * 更换密码
     */
    private void changePwd() {
        String newPwd = mNewPhone.getText().toString();
        String newPwdConfirm = mNewPhoneConfirm.getText().toString();
        if (TextUtils.isEmpty(newPwd)) {
            ToastUtil.showShort(R.string.setting_phone_pwd_null_tips);
            return;
        }
        if (TextUtils.isEmpty(newPwdConfirm)) {
            ToastUtil.showShort(R.string.setting_phone_pwd_null_tips);
            return;
        }
        if (!newPwdConfirm.equals(newPwd)) {
            ToastUtil.showShort(R.string.setting_phone_pwd_new_pwd_tip);
            return;
        }
        String md5Pwd = getMd5(newPwd);
        HashMap hashMap = new HashMap();
        hashMap.put(KEY_PASSWORD, md5Pwd);
        hashMap.put(KEY_TOKEN, HelperApplication.getToken());
        JSONObject data2 = new JSONObject(hashMap);
        ApiResultCallback requestCallback = new DefaultApiResult() {
            @Override
            public void onSuccess(JsonObject data) {
                quitAndLogin();
            }
        };
        ServerApi.post(ApiEnum.APP_UPDATE_USER_API.getUrl(), data2, null, progress, d -> addDisposable(d), requestCallback);
    }
}
